#! /usr/bin/python
# _*_ coding: utf-8 _*_

'在命令行玩'

__author__ = 'alanpo'

import maps, getkey
import os, threading

#初始化游戏常量
SIZE = (22, 52)  #棋盘尺寸
LONG = 5  #初始蛇长
FOOD = 3  #盘面食物数
#初始化棋盘
map = maps.Maps(SIZE[0], SIZE[1])
map.set_snake(LONG).put_food(FOOD)


#玩家操作
def player_jobs():
    while 1:
        ch = getkey.Getch()
        c = ch()
        if c == 'w' or 'A' in c:
            map.do_turn(2)
        elif c == 's' or 'B' in c:
            map.do_turn(4)
        elif c == 'a' or 'D' in c:
            map.do_turn(1)
        elif c == 'd' or 'C' in c:
            map.do_turn(3)
        elif c == 'q':
            # os.system('echo -e "\033[?25h"')
            os.system('stty echo')
            os.system('stty cooked')
            os.system('clear')
            os._exit(1)
        else:
            pass


#创建线程处理玩家操作
class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        player_jobs()


#开始游戏
def play():
    os.system('echo -e "\033[H"')  #光标位置回原点
    os.system('clear')
    os.system('stty -echo')
    os.system('echo -e "\033[?25l"')  #隐藏光标
    map.show_welcome().sleep()
    #创建玩家操作线程并启动
    thread1 = myThread(1, "Thread-1", 1)
    thread1.start()

    while 1:
        map.judge_to_turn()
        if map.do_move():
            print('啊哈!大侠请重新来过!')
            map.sleep()
            break
        map.show().sleep()
    os.system('clear')

    print("Sorce:", format(map.score))
    map.speed = 1000
    map.sleep()
    os.system('echo -e "\033[?25h"')  #显示光标
    os.system('echo -e "\033[H"')  #光标位置回原点
    os.system('clear')
    os.system('stty echo')
    os.system('stty cooked')
    os._exit(0)


if __name__ == '__main__':
    play()
